<?php
    /*  
    Captcha-Generator
    
    Copyright (C) 2009  Maik Kellerhals

    Captcha-Generator is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.
      
    Captcha-Generator is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.
  
    You should have received a copy of the GNU General Public License
    along with Foobar.  If not, see <http://www.gnu.org/licenses/>.
    */


    $CAPTCHA_LENGTH = 5;    // length of captcha in letters
    $FONT_SIZE      = 32;   // font size
    $IMG_WIDTH      = 300;  // width of image
    $IMG_HEIGHT     = 60;   // height of image

    // list of used fonts
    $FONTS[] = 'BILLD___.TTF';
    $FONTS[] = 'ELRIOTT2.TTF';

    // define used letters
    $ALPHABET = array('A', 'B', 'C', 'D', 'E', 'F', 'G',
                      'H', 'Q', 'J', 'K', 'M', 'N', 'P', 
                      'R', 'S', 'T', 'U', 'V', 'Y', 'W');

    // declare header
    header('Content-Type: image/jpeg', true);
    
    // start session (needs to be in main document as well)
    session_start();

    // create empty jpeg-image
    $img = imagecreatetruecolor($IMG_WIDTH, $IMG_HEIGHT);

    // define random light color for background
    $col = imagecolorallocate($img, rand(200, 255), rand(200, 255), rand(200, 255));

    // fill background with $col
    imagefill($img, 0, 0, $col);

    $captcha = ''; // container for captcha-string
    $x = 50; // x-offset from the left to first letter

    for($i = 0; $i < $CAPTCHA_LENGTH; $i++) {

        $chr = $ALPHABET[rand(0, count($ALPHABET) - 1)]; // get random letter from defined alphabet
        $captcha .= $chr; // add the letter to the string

        $col = imagecolorallocate($img, rand(0, 199), rand(0, 199), rand(0, 199)); // generate random darker color
        $font = $FONTS[rand(0, count($FONTS) - 1)]; // get random font from font list

        $y = 40 + rand(0, 10); // defin y-coordinate
        $angle = rand(-20, 20); // random angle between -20 and 20 degrees

        imagettftext($img, $FONT_SIZE, $angle, $x, $y, $col, $font, $chr);

        $dim = imagettfbbox($FONT_SIZE, $angle, $font, $chr); // get space required for letter
        $x += $dim[4] + abs($dim[6]) + 10; // allocate proper distance between letters
    }
    imagejpeg($img); // output image
    imagedestroy($img); // free memory
    $_SESSION['captcha'] = $captcha; // save captcha-string to session variable
?>